package com.wjx.admin_consumer.controller;


import com.wjx.admin_consumer.model.Appointment;
import com.wjx.admin_consumer.model.Rating;
import com.wjx.admin_consumer.model.Serve;
import com.wjx.admin_consumer.model.User;
import com.wjx.admin_consumer.service.AdminService;
import com.wjx.admin_consumer.tool.Tool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Controller
public class AdminController {
    @Autowired
    private AdminService adminService;
    @GetMapping("/login")
    public String login(int id, HttpSession session)     {
        session.setAttribute("user",adminService.queryUserById(id));
        return "redirect:/index";
    }
    @GetMapping("/quit")
    public String quit(HttpSession session){
        session.removeAttribute("user");
        return "redirect:http://localhost:8006/toLogin";
    }
    @GetMapping("/index")
    public String index(Model model, HttpSession session)     {
        model.addAttribute("index", 1);
        return "admin/index";
    }

    @GetMapping("/adminAppointment")
    public String adminAppointment(Model model)     {
        model.addAttribute("index", 0);
        model.addAttribute("adminAppointment", 1);
        model.addAttribute("queryAppointment", 1);
        List<Appointment> appointmentList = adminService.queryAllAppointment();
        model.addAttribute("appointmentList", appointmentList);
        List<Serve> serviceList = new ArrayList<>();
        List<User> userList = new ArrayList<>();
        for (Appointment appointment : appointmentList) {
            serviceList.add(adminService.queryServiceById(appointment.getServiceId()));
            userList.add(adminService.queryUserById(appointment.getUserId()));
        }
        model.addAttribute("serviceList", serviceList);
        model.addAttribute("userList", userList);
        return "admin/index";
    }

    @GetMapping("/toEditAppointment")
    public String toEditAppointment(int id, Model model)     {
        model.addAttribute("index", 0);
        model.addAttribute("adminAppointment", 1);
        model.addAttribute("queryAppointment", 0);
        model.addAttribute("editAppointment", 1);
        Appointment appointment = adminService.queryAppointmentById(id);
        Serve service = adminService.queryServiceById(appointment.getServiceId());
        User user = adminService.queryUserById(appointment.getUserId());
        model.addAttribute("appointment", appointment);
        model.addAttribute("service", service);
        model.addAttribute("user", user);
        return "admin/index";
    }

    @PostMapping("/editAppointment")
    public void editAppointment(String serviceName, String username, int id,
                                String appointmentTime, String appointmentLocation,
                                String phone,String status, HttpServletResponse response)
                                throws Exception {
        int userId = adminService.selectUserByUsername(username).getId();
        int serviceId = adminService.queryServiceByName(serviceName).getId();
        int temp = adminService.updateAppointmentById(id,userId,serviceId,appointmentTime,
                appointmentLocation,phone,status,new Tool().currentTime());
        if (temp >= 1) {
            response.getWriter().write("<script>alert('编辑成功，返回预约管理页面！');" +
                    "window.location.href='/adminAppointment'</script>");
        } else {
            response.getWriter().write("<script>alert('编辑失败，返回预约管理页面！');window.location.href='/adminAppointment'</script>");
        }
    }

    @GetMapping("/deleteAppointment")
    public void deleteAppointment(int id, HttpServletResponse response) throws Exception {
        adminService.deleteRatingByAppointmentId(id);
        int temp = adminService.deleteAppointmentById(id);
        if (temp >= 1) {
            response.getWriter().write("<script>alert('删除成功，返回预约管理页面！');" +
                    "window.location.href='/adminAppointment'</script>");
        } else {
            response.getWriter().write("<script>alert('删除失败，返回预约管理页面！');" +
                    "window.location.href='/adminAppointment'</script>");
        }
    }

    @PostMapping("/searchAdminAppointment")
    public String searchAdminAppointment(String keyword, Model model) throws Exception {
        model.addAttribute("index", 0);
        model.addAttribute("adminAppointment", 1);
        model.addAttribute("queryAppointment", 1);
        List<Appointment> appointmentList = new ArrayList<>();
        User user = adminService.selectUserByUsername(keyword);
        if (user != null && user.getUsername() != null && !Objects.equals(user.getUsername(), "")) {
            appointmentList = adminService.queryAppointmentByUserId(user.getId());
            model.addAttribute("appointmentList", appointmentList);
            List<Serve> serviceList = new ArrayList<>();
            List<User> userList = new ArrayList<>();
            for (Appointment appointment : appointmentList) {
                serviceList.add(adminService.queryServiceById(appointment.getServiceId()));
                userList.add(user);
            }
            model.addAttribute("serviceList", serviceList);
            model.addAttribute("userList", userList);
            return "admin/index";
        }

        Serve serve = adminService.queryServiceByName(keyword);
        if (serve != null && serve.getName() != null && !Objects.equals(serve.getName(), "")) {
            appointmentList = adminService.queryAppointmentByServiceId(serve.getId());
            model.addAttribute("appointmentList", appointmentList);
            List<Serve> serviceList = new ArrayList<>();
            List<User> userList = new ArrayList<>();
            for (Appointment appointment : appointmentList) {
                serviceList.add(serve);
                userList.add(adminService.queryUserById(appointment.getUserId()));
            }
            model.addAttribute("serviceList", serviceList);
            model.addAttribute("userList", userList);
            return "admin/index";
        }
        appointmentList = adminService.queryLikeAppointment(keyword);
        model.addAttribute("appointmentList", appointmentList);
        List<Serve> serviceList = new ArrayList<>();
        List<User> userList = new ArrayList<>();
        for (Appointment appointment : appointmentList) {
            serviceList.add(adminService.queryServiceById(appointment.getServiceId()));
            userList.add(adminService.queryUserById(appointment.getUserId()));
        }
        model.addAttribute("serviceList", serviceList);
        model.addAttribute("userList", userList);
        return "admin/index";
    }

    @GetMapping("/adminUser")
    public String adminUser(Model model)     {
        model.addAttribute("adminUser", 1);
        model.addAttribute("adminQueryUser", 1);
        model.addAttribute("userList", adminService.queryAllUser());
        return "admin/index";
    }

    @PostMapping("/searchUser")
    public String searchUser(String keyword, Model model)     {
        model.addAttribute("adminUser", 1);
        model.addAttribute("adminQueryUser", 1);
        model.addAttribute("userList", adminService.queryLikeUsername(keyword));
        return "admin/index";
    }

    @GetMapping("/toEditAdminUser")
    public String toEditAdminUser(int id, Model model)     {
        model.addAttribute("adminUser", 1);
        model.addAttribute("editAdminUser", 1);
        model.addAttribute("user", adminService.queryUserById(id));
        return "admin/index";
    }

    @PostMapping("/editAdminUser")
    public void editAdminUser(int id,String username,String password,String authority ,
                              HttpServletResponse response) throws Exception {
        int temp = adminService.updateUserById(id,username,password,authority);
        if (temp >= 1) {
            response.getWriter().write("<script>alert('编辑成功，返回用户管理页面！');" +
                    "window.location.href='/adminUser'</script>");
        } else {
            response.getWriter().write("<script>alert('编辑失败，返回用户管理页面！');" +
                    "window.location.href='/adminUser'</script>");
        }
    }

    @GetMapping("/deleteUser")
    public void deleteUser(int id, HttpServletResponse response) throws Exception {
        adminService.deleteAppointmentByUserId(id);
        adminService.deleteRatingByUserId(id);
        int temp = adminService.deleteUserById(id);
        if (temp >= 1) {
            response.getWriter().write("<script>alert('删除成功，返回用户管理页面！');" +
                    "window.location.href='/adminUser'</script>");
        } else {
            response.getWriter().write("<script>alert('删除失败，返回用户管理页面！');" +
                    "window.location.href='/adminUser'</script>");
        }
    }

    @GetMapping("/adminService")
    public String adminService(Model model)     {
        model.addAttribute("adminService", 1);
        model.addAttribute("adminQueryService", 1);
        model.addAttribute("serviceList", adminService.showService());
        return "/admin/index";
    }

    @PostMapping("/searchService")
    public String searchService(String keyword, Model model)     {
        model.addAttribute("adminService", 1);
        model.addAttribute("adminQueryService", 1);
        model.addAttribute("serviceList", adminService.search(keyword));
        return "/admin/index";
    }

    @GetMapping("/toEditAdminService")
    public String toEditAdminService(int id, Model model)     {
        model.addAttribute("adminService", 1);
        model.addAttribute("editAdminService", 1);
        model.addAttribute("service", adminService.queryServiceById(id));
        return "admin/index";
    }

    @PostMapping("/editAdminService")
    public void editAdminService(int id,String name,String description,double  price ,
                                 HttpServletResponse response) throws Exception {
        int temp = adminService.updateServiceById(id,name,description,price);
        if (temp >= 1) {
            response.getWriter().write("<script>alert('编辑成功，返回服务管理页面！');" +
                    "window.location.href='/adminService'</script>");
        } else {
            response.getWriter().write("<script>alert('编辑失败，返回服务管理页面！');" +
                    "window.location.href='/adminService'</script>");
        }
    }

    @GetMapping("/deleteService")
    public void deleteService(int id, HttpServletResponse response) throws Exception {
        adminService.deleteAppointmentByServiceId(id);
        adminService.deleteRatingByServiceId(id);
        int temp = adminService.deleteServiceById(id);
        if (temp >= 1) {
            response.getWriter().write("<script>alert('删除成功！');" +
                    "window.location.href='/adminService'</script>");
        } else {
            response.getWriter().write("<script>alert('删除失败！');" +
                    "window.location.href='/adminService'</script>");
        }
    }

    @GetMapping("/toAdminAddService")
    public String toAdminAddService(Model model) {
        model.addAttribute("adminAddService", 1);
        return "admin/index";
    }

    @PostMapping("/adminAddService")
    public void adminAddService(String name, String description, double price,
                                HttpServletResponse response) throws Exception {
        if (adminService.queryServiceByName(name) != null &&
                !adminService.queryServiceByName(name).getName().equals("")) {
            response.getWriter().write("<script>alert('添加失败！该清洁服务名称已存在');" +
                    "window.location.href='/adminService'</script>");
            return;
        }
        int temp = adminService.insertService(name,description,price);
        if (temp >= 1) {
            response.getWriter().write("<script>alert('添加成功！');" +
                    "window.location.href='/adminService'</script>");
        } else {
            response.getWriter().write("<script>alert('添加失败！');" +
                    "window.location.href='/adminAddService'</script>");
        }
    }
    @GetMapping("/AdminRating")
    public String AdminRating(Model model)     {
        model.addAttribute("AdminRating",1);
        List<Rating> ratingList = adminService.queryAllRating();
        model.addAttribute("ratingList",ratingList);
        List<User> userList = new ArrayList<>();
        List<Serve> serviceList = new ArrayList<>();
        for(Rating rating:ratingList){
            userList.add(adminService.queryUserById(rating.getUserId()));
            serviceList.add(adminService.queryServiceById(rating.getServiceId()));
        }
        model.addAttribute("serviceList",serviceList);
        model.addAttribute("userList",userList);
        return "admin/index";
    }
    @PostMapping("/searchRating")
    public String searchRating(String keyword,Model model)     {
        model.addAttribute("AdminRating",1);
        User user = adminService.selectUserByUsername(keyword);
        Serve serve = adminService.queryServiceByName(keyword);
        List<Rating> ratingList = new ArrayList<>();
        List<User> userList = new ArrayList<>();
        List<Serve> serviceList = new ArrayList<>();
        if(user != null && !user.getUsername().equals("")){
            ratingList = adminService.queryRatingByUserId(user.getId());
            for (Rating rating : ratingList){
                userList.add(user);
                serviceList.add(adminService.queryServiceById(rating.getServiceId()));
            }
        } else if (serve != null && !serve.getName().equals("")) {
            ratingList = adminService.queryRatingByServiceId(serve.getId());
            for (Rating rating : ratingList){
                userList.add(adminService.queryUserById(rating.getUserId()));
                serviceList.add(serve);
            }
        }else {
            ratingList = adminService.queryLikeRating(keyword);
            for (Rating rating : ratingList){
                userList.add(adminService.queryUserById(rating.getUserId()));
                serviceList.add(adminService.queryServiceById(rating.getServiceId()));
            }
        }
        model.addAttribute("ratingList",ratingList);
        model.addAttribute("userList",userList);
        model.addAttribute("serviceList",serviceList);
        return "admin/index";
    }
    @GetMapping("/adminDeleteRating")
    public void deleteRating(int id, HttpServletResponse response) throws Exception {
        int temp = adminService.deleteRatingById(id);
        if (temp >= 1) {
            response.getWriter().write("<script>alert('删除成功！');" +
                    "window.location.href='/AdminRating'</script>");
        } else {
            response.getWriter().write("<script>alert('删除失败！');" +
                    "window.location.href='/AdminRating'</script>");
        }
    }
    @GetMapping("/toAdminAddUser")
    public String toAdminAddUser(Model model){
        model.addAttribute("adminAddUser",1);
        return "admin/index";
    }
    @PostMapping("/adminAddUser")
    public void adminAddUser(String username,String password,String authority,
                            HttpServletResponse response) throws Exception{
        User user = adminService.selectUserByUsername(username);
        if (user != null && user.getUsername() != null && user.getUsername().equals(username)) {
            response.getWriter().write("<script>alert('用户名已存在！');" +
                    "window.location.href='/toAdminAddUser'</script>");
            return;
        }
        int temp = adminService.register(username,password,authority);
        if (temp >= 1) {
            response.getWriter().write("<script>alert('添加成功！');" +
                    "window.location.href='/toAdminAddUser'</script>");
        } else {
            response.getWriter().write("<script>alert('添加失败！');" +
                    "window.location.href='/toAdminAddUser'</script>");
        }
    }
}
